package com.cy.demo.controller;

import com.cy.demo.pojo.CartVO;
import com.cy.demo.service.ICartService;
import com.cy.demo.utils.jsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("carts")
@RestController
public class CartController extends BaseController{

    @Autowired
    private ICartService cartService;

    /**
     *插入商品到购物车 接口
     * @param pid 商品id
     * @param amount 商品数量
     * @param session 当前session 用于获取用户id与用户名
     */
    @GetMapping("/add_to_cart")
    public jsonResult<Void> addToCart(int pid,
                                      int amount,
                                      HttpSession session){
        cartService.addToCart(getuidFromSession(session), pid, amount,getUsernameFromSession(session));

        return new jsonResult<>(OK);
    }


    @GetMapping({"","/"})
    public jsonResult<List<CartVO>> getVOByUid(HttpSession session){
        int uid = getuidFromSession(session);

        List<CartVO> data = cartService.getVOByUid(uid);

        return new jsonResult<List<CartVO>>(data,OK);
    }

    @RequestMapping("/addNum/{AorP}/{cid}")
    public jsonResult<Integer> addNum(@PathVariable("cid") int cid,HttpSession session,@PathVariable("AorP") boolean AorP) throws Exception {
        int uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);

        int data = cartService.addNum(cid,uid,username,AorP);

        return new jsonResult<Integer>(data,OK);
    }

    @RequestMapping("/delete/{cid}")
    public jsonResult<Void> deleteByCid(@PathVariable ("cid") int cid) throws Exception {
        cartService.deleteByCid(cid);
        return  new jsonResult<>(OK);
    }


    @RequestMapping("list")
    public jsonResult<List<CartVO>> getVOByUid(HttpSession session,int[] cids) throws Exception {


        List<CartVO> data = cartService.getVOByCids(getuidFromSession(session),cids);

        return new jsonResult<List<CartVO>>(data,OK);

    }
}
